

function modify_port_val(port) {
    layer.open({
        type: 1,
        area: '400px',
        title: '修改端口',
        closeBtn: 2,
        shadeClose: false,
        btn: ['确认', '取消'],
        content: '<div class="bt-form pd20 pd70" style="padding:20px 35px;">\
				<ul style="margin-bottom:10px;color:red;width: 100%;background: #f7f7f7;padding: 10px;border-radius: 5px;font-size: 12px;">\
					<li style="color:red;font-size:13px;">1、有安全组的服务器请提前在安全组放行新端口</li>\
					<li style="color:red;font-size:13px;">2、如果修改端口导致面板无法访问，请在SSH命令行通过bt命令改回原来的端口</li>\
				</ul>\
				<div class="line">\
	                <span class="tname" style="width: 70px;">面板端口</span>\
	                <div class="info-r" style="margin-left:70px">\
	                    <input name="portss" class="bt-input-text mr5" type="text" style="width:200px" value="'+ port + '">\
	                </div>\
                </div>\
                <div class="details" style="margin-top:5px;padding-left: 3px;">\
					<input type="checkbox" id="check_port">\
					<label style="font-weight: 400;margin: 3px 5px 0px;" for="check_port">我已了解</label>,<a target="_blank" class="btlink" href="https://www.bt.cn/bbs/thread-40037-1-1.html">如何放行端口？</a>\
				</div>\
			</div>',
        yes: function (index, layero) {
            var check_port = $('#check_port').prop('checked'), _tips = '';
            if (!check_port) {
                _tips = layer.tips('请勾选我已了解', '#check_port', { tips: [1, '#ff0000'], time: 5000 });
                return false;
            }
            layer.close(_tips);
            $('#banport').val($('[name="portss"]').val());
            var _data = $("#set-Config").serializeObject();
            _data['port'] = $('[name="portss"]').val();
            var loadT = layer.msg(lan.config.config_save, { icon: 16, time: 0, shade: [0.3, '#000'] });
            $.post('/config?action=setPanel', _data, function (rdata) {
                layer.close(loadT);
                layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 });
                if (rdata.status) {
                    layer.close(index);
                    setTimeout(function () {
                        window.location.href = ((window.location.protocol.indexOf('https') != -1) ? 'https://' : 'http://') + rdata.host + window.location.pathname;
                    }, 4000);
                }
            });
        },
        success: function () {
            $('#check_port').click(function () {
                layer.closeAll('tips');
            });
        }
    });
}
$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
$('#show_recommend').click(function () {
    var status = !$(this).prop("checked"), that = $(this);
    layer.confirm(status ? '关闭活动推荐，将无法接受到宝塔官方推荐的活动内容？' : '开启活动推荐，定期获取宝塔官方推荐的的活动内容！', {
        title: status ? '关闭活动推荐' : '开启活动推荐', closeBtn: 2, icon: 13, cancel: function () {
            that.prop("checked", status);
        }
    }, function () {
        $.post('/config?action=show_recommend', function (rdata) {
            layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 });
        });
    }, function () {
        that.prop("checked", status);
    });

})

$('#auto_update_panel').click(function () {
    var status = !$(this).prop("checked"), that = $(this);
    layer.confirm(status ? '关闭自动更新，将无法自动更新面板到最新版本？' : '开启自动更新，将会通过计划任务定时将面板更新到最新版本<br>(说明：更新面板不会影响网站环境)', {
        title: status ? '关闭自动更新' : '开启自动更新', closeBtn: 2, icon: 13, cancel: function () {
            that.prop("checked", status);
        }
    }, function () {
            $.post('/config?action=auto_update_panel', function (rdata) {
            layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 });
        });
    }, function () {
        that.prop("checked", status);
    });
})


$('#show_workorder').click(function () {
    var status = !$(this).prop("checked"), that = $(this);
    layer.confirm(status ? '关闭BUG反馈，将无法实时向宝塔技术人员反馈问题？' : '开启BUG反馈，实时向宝塔技术人员反馈问题？', {
        title: status ? '关闭活动推荐' : '开启活动推荐', closeBtn: 2, icon: 13, cancel: function () {
            that.prop("checked", status);
        }
    }, function () {
        $.post('/config?action=show_workorder', function (rdata) {
            layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 });
            window.location.reload();
        });
    }, function () {
        that.prop("checked", status);
    });
});
$('#panel_verification').click(function () {
    var _checked = $(this).prop('checked');
    if (_checked) {
        layer.open({
            type: 1,
            area: ['500px', '530px'],
            title: '动态口令设置',
            closeBtn: 2,
            shift: 5,
            shadeClose: false,
            content: '<div class="bt-form pd20 pd70 ssl_cert_from" style="padding:20px 35px;">\
				<div class="">\
					<i class="layui-layer-ico layui-layer-ico3"></i>\
					<h3>危险！此功能不懂别开启!</h3>\
					<ul style="width:91%;margin-bottom:10px;margin-top:10px;">\
						<li style="color:red;">必须要用到且了解此功能才决定自己是否要开启!</li>\
						<li style="color:red;">如果无法验证，命令行输入"bt 24" 取消动态口令认证</li>\
						<li>开启服务后，请立即绑定，以免出现面板不能访问。</li>\
						<li>请先下载宝塔APP或(谷歌认证器)，并完成安装和初始化</li>\
						<li>基于google Authenticator 开发,如遇到问题请点击<a target="_blank" class="btlink" href="https://www.bt.cn/bbs/forum.php?mod=viewthread&tid=37437">了解详情</a></li>\
					</ul>\
				</div>\
				<div class="download_Qcode">\
					<div class="item_down">\
						<div class="qcode_title">Android/IOS应用 扫码下载</div>\
						<div class="qcode_conter"><img src="/static/img/bt_app.png" /></div>\
					</div>\
				</div>\
				<div class="details" style="width: 90%;margin-bottom:10px;">\
					<input type="checkbox" id="check_verification">\
					<label style="font-weight: 400;margin: 3px 5px 0px;" for="check_verification">我已安装APP和了解详情,并愿意承担风险！</label>\
				</div>\
				<div class="bt-form-submit-btn">\
					<button type="button" class="btn btn-sm btn-danger close_verify">关闭</button>\
					<button type="button" class="btn btn-sm btn-success submit_verify">确认</button>\
				</div>\
			</div>',
            success: function (layers, index) {
                $('.submit_verify').click(function (e) {
                    var check_verification = $('#check_verification').prop('checked');
                    if (!check_verification) {
                        layer.msg('请先勾选同意风险', { icon: 0 });
                        return false;
                    }
                    var loadT = layer.msg('正在开启动态口令认证，请稍后...', { icon: 16, time: 0, shade: [0.3, '#000'] });
                    set_two_step_auth({ act: _checked }, function (rdata) {
                        layer.close(loadT);
                        if (rdata.status) layer.closeAll();
                        layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 });
                        if (rdata.status && _checked) {
                            $('.open_two_verify_view').click();
                        }
                    });
                });
                $('.close_verify').click(function () {
                    layer.closeAll();
                    $('#panel_verification').prop('checked', !_checked);
                });
            }, cancel: function () {
                layer.closeAll();
                $('#panel_verification').prop('checked', !_checked);
            }
        });
    } else {
        bt.confirm({
            title: '动态口令认证',
            msg: '是否关闭动态口令认证，是否继续？',
            cancel: function () {
                $('#panel_verification').prop('checked', !_checked);
            }
        }, function () {
            var loadT = layer.msg('正在关闭动态口令认证，请稍后...', { icon: 16, time: 0, shade: [0.3, '#000'] });
            set_two_step_auth({ act: _checked }, function (rdata) {
                layer.close(loadT);
                if (rdata.status) layer.closeAll();
                layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 });
                if (rdata.status && _checked) {
                    $('.open_two_verify_view').click();
                }
            });
        }, function () {
            $('#panel_verification').prop('checked', !_checked);
        });
    }

    // console.log(_data);

});

$('.open_two_verify_view').click(function () {
    var _checked = $('#panel_verification').prop('checked');
    if (!_checked) {
        layer.msg('请先开启Google身份认证服务', { icon: 0 });
        return false;
    }
    layer.open({
        type: 1,
        area: ['600px', '670px'],
        title: 'Google身份认证绑定',
        closeBtn: 2,
        shift: 5,
        shadeClose: false,
        content: '<div class="bt-form pd20" style="padding:20px 35px;">\
					<div class="verify_title">基于Google Authenticator用户进行登录认证</div>\
					<div class="verify_item">\
						<div class="verify_vice_title">1. 密钥绑定</div>\
						<div class="verify_conter">\
							<div class="verify_box">\
								<div class="verify_box_line">账号：<span class="username"></sapn></div>\
								<div class="verify_box_line">密钥：<span class="userkey"></sapn></div>\
								<div class="verify_box_line">类型：<span class="usertype">基于时间</sapn></div>\
							</div>\
						</div>\
					</div>\
					<div class="verify_item">\
						<div class="verify_vice_title">2. 扫码绑定 （ 使用Google 身份验证器APP扫码 ）</div>\
						<div class="verify_conter" style="text-align:center;padding-top:10px;">\
							<div id="verify_qrcode"></div>\
						</div>\
					</div>\
					<div class="verify_tips">\
						<p>提示：请使用“ Google 身份验证器APP ”绑定,各大软件商店均可下载该APP，支持安卓、IOS系统。<a href="https://www.bt.cn/bbs/forum.php?mod=viewthread&tid=37437" class="btlink" target="_blank">使用教程</a></p>\
						<p style="color:red;">开启服务后，请立即使用“Google 身份验证器APP”绑定，以免出现无法登录的情况。</p>\
					</div>\
				</div>',
        success: function (e) {
            get_two_verify(function (res) {
                $('.verify_box_line .username').html(res.username);
                $('.verify_box_line .userkey').html(res.key);
            });
            get_qrcode_data(function (res) {
                jQuery('#verify_qrcode').qrcode({
                    render: "canvas",
                    text: res,
                    height: 150,
                    width: 150
                });
            });
        }
    });
});

(function () {
    check_two_step(function (res) {
        $('#panel_verification').prop('checked', res.status);
    });
    get_msg_configs(function(res){
    	var txt_ = '';
    	$.each(res,function(index,item){
    		if(item['setup']){
    			if($.isEmptyObject(item['data'])){
    				txt_ += item['title'] + '未配置 | '
    			}else{
    				txt_ += item['title'] + '已配置 | '
    			}
    		}
    	})
		$('#channel_auth').val(bt.rtrim(txt_,'| '))
    })
})()
function get_msg_configs(callback){
	$.post('/config?action=get_msg_configs', function (res) {
        if (callback) callback(res);
    });
}

function check_two_step(callback) {
    $.post('/config?action=check_two_step', function (res) {
        if (callback) callback(res);
    });
}
function get_qrcode_data(callback) {
    $.post('/config?action=get_qrcode_data', function (res) {
        if (callback) callback(res);
    });
}
function get_two_verify(callback) {
    $.post('/config?action=get_key', function (res) {
        if (callback) callback(res);
    });
}
function set_two_step_auth(obj, callback) {
    $.post('/config?action=set_two_step_auth', { act: obj.act ? 1 : 0 }, function (res) {
        if (callback) callback(res);
    });
}

//关闭面板
function ClosePanel(){
	layer.confirm(lan.config.close_panel_msg,{title:lan.config.close_panel_title,closeBtn:2,icon:13,cancel:function(){
		$("#closePl").prop("checked",false);
	}}, function() {
		$.post('/config?action=ClosePanel','',function(rdata){
			layer.msg(rdata.msg,{icon:rdata.status?1:2});
			setTimeout(function(){window.location.reload();},1000);
		});
	},function(){
		$("#closePl").prop("checked",false);
	});
}

//设置自动更新
function SetPanelAutoUpload(){
	loadT = layer.msg(lan.public.config,{icon:16,time:0});
	$.post('/config?action=AutoUpdatePanel','',function(rdata){
		layer.close(loadT);
		layer.msg(rdata.msg,{icon:rdata.status?1:2});
	});
}


$(".set-submit").click(function(){
	var data = $("#set-Config").serialize();
	layer.msg(lan.config.config_save,{icon:16,time:0,shade: [0.3, '#000']});
	$.post('/config?action=setPanel',data,function(rdata){
		layer.closeAll();
		layer.msg(rdata.msg,{icon:rdata.status?1:2});
		if(rdata.status){
			setTimeout(function(){
				window.location.href = ((window.location.protocol.indexOf('https') != -1)?'https://':'http://') + rdata.host + window.location.pathname;
			},1500);
		}
	});
	
});


function syncDate(){
	var loadT = layer.msg(lan.config.config_sync,{icon:16,time:0,shade: [0.3, '#000']});
	$.post('/config?action=syncDate','',function(rdata){
		layer.close(loadT);
		layer.msg(rdata.msg,{icon:1});
		setTimeout(function(){
				window.location.reload();
			},1500);
	});
}

//PHP守护程序
function Set502(){
	var loadT = layer.msg(lan.public.the,{icon:16,time:0,shade: [0.3, '#000']});
	$.post('/config?action=Set502','',function(rdata){
		layer.close(loadT);
		layer.msg(rdata.msg,{icon:rdata.status?1:2});
	});	
}

//绑定修改宝塔账号
function bindBTName(a,type){
	var titleName = lan.config.config_user_binding;
	if(type == "b"){
		btn = "<button type='button' class='btn btn-success btn-sm' onclick=\"bindBTName(1,'b')\">"+lan.config.binding+"</button>";
	}
	else{
		titleName = lan.config.config_user_edit;
		btn = "<button type='button' class='btn btn-success btn-sm' onclick=\"bindBTName(1,'c')\">"+lan.public.edit+"</button>";
	}
	if(a == 1) {
		p1 = $("#p1").val();
		p2 = $("#p2").val();
		var loadT = layer.msg(lan.config.token_get,{icon:16,time:0,shade: [0.3, '#000']});
		$.post(" /ssl?action=GetToken", "username=" + p1 + "&password=" + p2, function(b){
			layer.close(loadT);
			layer.msg(b.msg, {icon: b.status?1:2});
			if(b.status) {
				window.location.reload();
				$("input[name='btusername']").val(p1);
			}
		});
		return
	}
	layer.open({
		type: 1,
		area: "290px",
		title: titleName,
		closeBtn: 2,
		shift: 5,
		shadeClose: false,
		content: "<div class='bt-form pd20 pb70'><div class='line'><span class='tname'>"+lan.public.user+"</span><div class='info-r'><input class='bt-input-text' type='text' name='username' id='p1' value='' placeholder='"+lan.config.user_bt+"' style='width:100%'/></div></div><div class='line'><span class='tname'>"+lan.public.pass+"</span><div class='info-r'><input class='bt-input-text' type='password' name='password' id='p2' value='' placeholder='"+lan.config.pass_bt+"' style='width:100%'/></div></div><div class='bt-form-submit-btn'><button type='button' class='btn btn-danger btn-sm' onclick=\"layer.closeAll()\">"+lan.public.cancel+"</button> "+btn+"</div></div>"
	})
}
//解除绑定宝塔账号
function UnboundBt(){
	var name = $("input[name='btusername']").val();
	layer.confirm(lan.config.binding_un_msg,{closeBtn:2,icon:3,title:lan.config.binding_un},function(){
		$.get("/ssl?action=DelToken",function(b){
			if(b.status){
				$("input[name='btusername']").val('');
				window.location.reload();
			}
			layer.msg(b.msg,{icon:b.status? 1:2})
		})
	})
}

//设置API
function apiSetup(){
	var loadT = layer.msg(lan.config.token_get,{icon:16,time:0,shade: [0.3, '#000']});
	$.get('/api?action=GetToken',function(rdata){
		layer.close(loadT);
		
	});
}


//设置模板
function setTemplate(){
	var template = $("select[name='template']").val();
	var loadT = layer.msg(lan.public.the,{icon:16,time:0,shade: [0.3, '#000']});
	$.post('/config?action=SetTemplates','templates='+template,function(rdata){
		layer.close(loadT);
		layer.msg(rdata.msg,{icon:rdata.status?1:5});
		if(rdata.status === true){
			$.get('/system?action=ReWeb',function(){});
			setTimeout(function(){
				window.location.reload();
			},3000);
		}
	});
}

//设置面板SSL
function setPanelSSL(){
	var status = $("#sshswitch").prop("checked")==true?1:0;
	var msg = $("#panelSSL").attr('checked')?lan.config.ssl_close_msg:'<a style="font-weight: bolder;font-size: 16px;">'+lan.config.ssl_open_ps+'</a><li style="margin-top: 12px;color:red;">'+lan.config.ssl_open_ps_1+'</li><li>'+lan.config.ssl_open_ps_2+'</li><li>'+lan.config.ssl_open_ps_3+'</li><p style="margin-top: 10px;"><input type="checkbox" id="checkSSL" /><label style="font-weight: 400;margin: 3px 5px 0px;" for="checkSSL">'+lan.config.ssl_open_ps_4+'</label><a target="_blank" class="btlink" href="https://www.bt.cn/bbs/thread-4689-1-1.html" style="float: right;">'+lan.config.ssl_open_ps_5+'</a></p>';
	layer.confirm(msg,{title:lan.config.ssl_title,closeBtn:2,icon:3,area:'550px',cancel:function(){
		if(status == 0){
			$("#panelSSL").prop("checked",false);
		}
		else{
			$("#panelSSL").prop("checked",true);
		}
	}},function(){
		if(window.location.protocol.indexOf('https') == -1){
			if(!$("#checkSSL").prop('checked')){
				layer.msg(lan.config.ssl_ps,{icon:2});
				return false;
			}
		}
		var loadT = layer.msg(lan.config.ssl_msg,{icon:16,time:0,shade: [0.3, '#000']});
		$.post('/config?action=SetPanelSSL','',function(rdata){
			layer.close(loadT);
			layer.msg(rdata.msg,{icon:rdata.status?1:5});
			if(rdata.status === true){
				$.get('/system?action=ReWeb',function(){});
				setTimeout(function(){
					window.location.href = ((window.location.protocol.indexOf('https') != -1)?'http://':'https://') + window.location.host + window.location.pathname;
				},1500);
			}
		});
	},function(){
		if(status == 0){
			$("#panelSSL").prop("checked",false);
		}
		else{
			$("#panelSSL").prop("checked",true);
		}
	});
}

function GetPanelSSL(){
	var loadT = layer.msg('正在获取证书信息...',{icon:16,time:0,shade: [0.3, '#000']});
	$.post('/config?action=GetPanelSSL',{},function(cert){
		layer.close(loadT);
		var certBody = '<div class="tab-con">\
			<div class="myKeyCon ptb15">\
				<div class="ssl-con-key pull-left mr20">密钥(KEY)<br>\
					<textarea id="key" class="bt-input-text">'+cert.privateKey+'</textarea>\
				</div>\
				<div class="ssl-con-key pull-left">证书(PEM格式)<br>\
					<textarea id="csr" class="bt-input-text">'+cert.certPem+'</textarea>\
				</div>\
				<div class="ssl-btn pull-left mtb15" style="width:100%">\
					<button class="btn btn-success btn-sm" onclick="SavePanelSSL()">保存</button>\
				</div>\
			</div>\
			<ul class="help-info-text c7 pull-left">\
				<li>粘贴您的*.key以及*.pem内容，然后保存即可<a href="http://www.bt.cn/bbs/thread-704-1-1.html" class="btlink" target="_blank">[帮助]</a>。</li>\
				<li>如果浏览器提示证书链不完整,请检查是否正确拼接PEM证书</li><li>PEM格式证书 = 域名证书.crt + 根证书(root_bundle).crt</li>\
			</ul>\
		</div>'
		layer.open({
			type: 1,
			area: "600px",
			title: '自定义面板证书',
			closeBtn: 2,
			shift: 5,
			shadeClose: false,
			content:certBody
		});
	});
}

function SavePanelSSL(){
	var data = {
		privateKey:$("#key").val(),
		certPem:$("#csr").val()
	}
	var loadT = layer.msg(lan.config.ssl_msg,{icon:16,time:0,shade: [0.3, '#000']});
	$.post('/config?action=SavePanelSSL',data,function(rdata){
		layer.close(loadT);
		if(rdata.status){
			layer.closeAll();
		}
		layer.msg(rdata.msg,{icon:rdata.status?1:2});
	});
}

if(window.location.protocol.indexOf('https') != -1){
	$("#panelSSL").attr('checked',true);
}

var weChat = {
		settiming:'',
		relHeight:500,
		relWidth:500,
		userLength:'',
		init:function(){
			var _this = this;
			$('.layui-layer-page').css('display', 'none');
			$('.layui-layer-page').width(_this.relWidth);
			$('.layui-layer-page').height(_this.relHeight);
			$('.bt-w-menu').height((_this.relWidth - 1) - $('.layui-layer-title').height());
			var width = $(document).width();
			var height = $(document).height();
			var boxwidth =  (width / 2) - (_this.relWidth / 2);
			var boxheight =  (height / 2) - (_this.relHeight / 2);
			$('.layui-layer-page').css({
				'left':boxwidth +'px',
				'top':boxheight+'px'
			});
			$('.boxConter,.layui-layer-page').css('display', 'block');
			$('.layui-layer-close').click(function(event) {
				window.clearInterval(_this.settiming);
			});
			this.getUserDetails();
			$('.iconCode').hide();
			$('.personalDetails').show();
		},
		// 获取二维码
		getQRCode:function(){
			var _this = this;
			var qrLoading = layer.msg('正在获取二维码,请稍后...',{time:0,shade: [0.4,'#fff'],icon:16});
			$.get('/wxapp?action=blind_qrcode', function(res) {
				layer.close(qrLoading);
				if (res.status){
                	$('#QRcode').empty();
					$('#QRcode').qrcode({
					    render: "canvas", //也可以替换为table
					    width: 200,
					    height: 200,
					    text:res.msg
					});
					// $('.QRcode img').attr('src', res.msg);
					_this.settiming =  setInterval(function(){
						_this.verifyBdinding();
					},2000);
				}else{
					layer.msg('无法获取二维码，请稍后重试',{icon:2});
				}
			});
		},
		// 获取用户信息
		getUserDetails:function(type){
			var _this = this;
			var conter = '';
			$.get('/wxapp?action=get_user_info',function(res){
				clearInterval(_this.settiming);
				if (!res.status){
					layer.msg(res.msg,{icon:2,time:3000});
					$('.iconCode').hide();
					return false;
				}
				if (JSON.stringify(res.msg) =='{}'){
					if (type){
						layer.msg('当前绑定列表为空,请先绑定然后重试',{icon:2});
					}else{
						_this.getQRCode();
					}
					$('.iconCode').show();
					$('.personalDetails').hide();
					return false;
				}
				$('.iconCode').hide();
				$('.personalDetails').show();
				var datas = res.msg;
				for(var item in datas){
					conter += '<li class="item">\
								<div class="head_img"><img src="'+datas[item].avatarUrl+'" title="用户头像" /></div>\
								<div class="nick_name"><span>昵称:</span><span class="nick"></span>'+datas[item].nickName+'</div>\
								<div class="cancelBind">\
									<a href="javascript:;" class="btlink" title="取消当前微信小程序的绑定" onclick="weChat.cancelBdinding('+ item +')">取消绑定</a>\
								</div>\
							</li>'
				}
				conter += '<li class="item addweChat" style="height:45px;"><a href="javascript:;" class="btlink" onclick="weChat.addweChatView()"><span class="glyphicon glyphicon-plus"></span>添加绑定账号</a></li>'
				$('.userList').empty().append(conter);
			});
		},
		// 添加绑定视图
		addweChatView:function(){
			$('.iconCode').show();
			$('.personalDetails').hide();
			this.getQRCode();
		},
		// 取消当前绑定
		cancelBdinding:function(uid){
			var _this = this;
			var bdinding = layer.confirm('您确定要取消当前绑定吗？',{
				btn:['确认','取消'],
				icon:3,
				title:'取消绑定'
			},function(){
				$.get('/wxapp?action=blind_del',{uid:uid}, function(res) {
					layer.msg(res.msg,{icon:res.status?1:2});
					_this.getUserDetails();
				});
			},function(){
				layer.close(bdinding);
			});
		},
		// 监听是否绑定
		verifyBdinding:function(){
			var _this = this;
			$.get('/wxapp?action=blind_result',function(res){
				if(res){
					layer.msg('绑定成功',{icon:1});
					clearInterval(_this.settiming);
					_this.getUserDetails();
				}
			});
		},
	}
	
function open_wxapp(){
	var rhtml = '<div class="boxConter" style="display: none">\
					<div class="iconCode" >\
						<div class="box-conter">\
							<div id="QRcode"></div>\
							<div class="codeTip">\
								<ul>\
									<li>1、打开宝塔面板小程序<span class="btlink weChat">小程序二维码<div class="weChatSamll"><img src="https://app.bt.cn/static/app.png"></div></span></li>\
									<li>2、使用宝塔小程序扫描当前二维码，绑定该面板</li>\
								</ul>\
								<span><a href="javascript:;" title="返回面板绑定列表" class="btlink" style="margin: 0 auto" onclick="weChat.getUserDetails(true)">查看绑定列表</a></span>\
							</div>\
						</div>\
					</div>\
					<div class="personalDetails" style="display: none">\
						<ul class="userList"></ul>\
					</div>\
				</div>'
	
	layer.open({
		type: 1,
		title: "绑定微信",
		area: '500px',
		closeBtn: 2,
		shadeClose: false,
		content:rhtml
	});
	
	weChat.init();
}

$(function () {

    $.get("/ssl?action=GetUserInfo", function (b) {
        if (b.status) {
            $("input[name='btusername']").val(b.data.username);
            $("input[name='btusername']").next().text(lan.public.edit).attr("onclick", "bt.pub.bind_btname(\'edit\')").css({ "margin-left": "-82px" });
            $("input[name='btusername']").next().after('<span class="btn btn-xs btn-success" onclick="UnboundBt()" style="vertical-align: 0px;">' + lan.config.binding_un + '</span>');
        }
        else {
            $("input[name='btusername']").next().text(lan.config.binding).attr("onclick", "bt.pub.bind_btname()").removeAttr("style");

        }
        bt_init();
    });
})

function bt_init() {
    var btName = $("input[name='btusername']").val();

    if (!btName) {
        $('.wxapp_p .inputtxt').val("未绑定宝塔账号");
        $('.wxapp_p .modify').attr("onclick", "");
    }
}


function SetIPv6() {
    var loadT = layer.msg('正在配置,请稍候...', { icon: 16, time: 0, shade: [0.3, '#000'] });
    $.post('/config?action=set_ipv6_status', {}, function (rdata) {
        layer.close(loadT);
        bt.msg(rdata);
    });
}

function GetPanelApi() {
    var loadT = layer.msg('正在获取API接口信息...', { icon: 16, time: 0, shade: [0.3, '#000'] });
    $.post('/config?action=get_token', {}, function (rdata) {
        layer.close(loadT);
        isOpen = rdata.open ? 'checked' : '';
        layer.open({
            type: 1,
            area: "500px",
            title: "配置面板API",
            closeBtn: 2,
            shift: 5,
            shadeClose: false,
            content: ' <div class="bt-form bt-form" style="padding:15px 25px">\
						<div class="line">\
							<span class="tname">API接口</span>\
							<div class="info-r" style="height:28px;">\
								<input class="btswitch btswitch-ios" id="panelApi_s" type="checkbox" '+ isOpen + '>\
								<label style="position: relative;top: 5px;" class="btswitch-btn" for="panelApi_s" onclick="SetPanelApi(2,0)"></label>\
							</div>\
						</div>\
                        <div class="line">\
                            <span class="tname">接口密钥</span>\
                            <div class="info-r">\
                                <input disabled="disabled" name="panel_token_value" class="bt-input-text mr5 disable" type="text" style="width: 310px" value="'+ rdata.token + '" disable>\
                                <button class="btn btn-xs btn-success btn-sm" style="margin-left: -50px;" onclick="SetPanelApi(1)">重置</button>\
                            </div>\
                        </div>\
                        <div class="line ">\
                            <span class="tname" style="overflow: initial;height:20px;line-height:20px;">IP白名单</br>(每行1个)</span>\
                            <div class="info-r">\
                                <textarea name="api_limit_addr" class="bt-input-text mr5" type="text" style="width: 310px;height:80px;line-height: 20px;padding: 5px 8px;margin-bottom:10px;">'+ rdata.limit_addr + '</textarea>\
                                <button class="btn btn-success btn-sm" onclick="SetPanelApi(3)">保存</button>\
                            </div>\
                        </div>\
                        <ul class="help-info-text c7">\
                            <li>开启API后，必需在IP白名单列表中的IP才能访问面板API接口</li>\
                            <li>接口密钥只要重置时显示1次，之后不再显示，请保管好您的密钥</li>\
                            <li>API接口文档在这里：<a class="btlink" href="https://www.bt.cn/bbs/thread-20376-1-1.html" target="_blank">https://www.bt.cn/bbs/thread-20376-1-1.html</a></li>\
                        </ul>\
                    </div>'
        })
    });
}


function SetPanelApi(t_type,index) {
    var pdata = {}
    pdata['t_type'] = t_type
    if (t_type == 3) {
        pdata['limit_addr'] = $("textarea[name='api_limit_addr']").val()
    }
    var loadT = layer.msg('正在提交...', { icon: 16, time: 0, shade: [0.3, '#000'] });
    $.post('/config?action=set_token', pdata, function (rdata) {
        if (t_type == 1) {
            if (rdata.status) {
                $("input[name='panel_token_value']").val(rdata.msg);
                layer.msg('接口密钥已生成，请保管好您的新密钥，此密钥只显示一次!', { icon: 1 });
                return;
            }
        }

        layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 });
        if (rdata.msg == '开启成功!') {
           if(t_type == 2 && index != '0') GetPanelApi();
        }
    })
}

function install_module() {
    var _item = $(".bt-w-menu p.bgw").data('data');
    var spt = '安装'
    if (_item.setup)  spt = '更新'
    
    layer.confirm('是否要' + spt+'【' + _item.title + '】模块', { title: '安装模块', closeBtn: 2, icon: 0 }, function () {
        var loadT = layer.msg('正在' + spt + _item.title + '模块中,请稍候...', { icon: 16, time: 0, shade: [0.3, '#000'] });
        $.post('/config?action=install_module&name=' + _item.name + '', function (res) {
            layer.close(loadT)
            get_msg_config()
            layer.msg(res.msg, { icon: res.status ? 1 : 2 })
        })
    })
}

function uninstall_module() {
    var _item = $(".bt-w-menu p.bgw").data('data');

    layer.confirm('是否确定要卸载【' + _item.title + '】模块', { title: '卸载模块', closeBtn: 2, icon: 0 }, function () {
        var loadT = layer.msg('正在卸载' + _item.title + '模块中,请稍候...', { icon: 16, time: 0, shade: [0.3, '#000'] });
        $.post('/config?action=uninstall_module&name=' + _item.name + '', function (res) {
            layer.close(loadT)
            get_msg_config()
            layer.msg(res.msg, { icon: res.status ? 1 : 2 })
        })
    })
}

function get_msg_config()
{
    $.post('/config?action=get_msg_configs', function (rdata) {
        var menu_data = $(".alarm-view .bt-w-menu p.bgw").data('data')
        $('.alarm-view .bt-w-menu').html('');
        $.each(rdata, function (index, item) {
            _menu = $('<p class=\'men_' + item['name'] + '\'>' + item['title'] + '</p>').data('data', item)
            $('.alarm-view .bt-w-menu').append(_menu)
        });
        
        $(".alarm-view .bt-w-menu p").click(function () {
            $(this).addClass('bgw').siblings().removeClass('bgw')
            var _item = $(this).data('data');

            var shtml = '<div class="plugin_user_info c7">\
                            <p><b>名称：</b>'+ _item.title +'</p>\
                            <p><b>版本：</b>'+ _item.version +'</p>\
                            <p><b>时间：</b>'+ _item.date +'</p>\
                            <p><b>描述：</b>'+ _item.ps + '</p>\
                            <p><b>说明：</b><a class="btlink" href="'+ _item.help + '" target=" _blank">' + _item.help +'</a></p>\
                            <p><button class="btn btn-success btn-sm mt10" onclick="install_module()" >安装模块</button></p>\
                     </div>'

            if (_item['setup']) {
                $.post('/config?action=get_module_template', { module_name: _item['name'] }, function (res) {
                    if (res.status) {
                        $(".bt-w-main .plugin_body").html(res.msg)

                        $(".bt-w-main .plugin_body").append('<div class="plugin_update" ><button class="btn btn-danger btn-sm" onclick="uninstall_module()" >卸载模块</button></div>')
                        if (_item['version'] != _item['info']['version']){
                            $(".bt-w-main .plugin_body").append('<div class="plugin_update" style="width:408px" >【' + _item['title'] + '】模块存在新的版本,为了不影响使用,请更新.<button class="btn btn-success btn-sm" onclick="install_module()" >立即更新</button></div>')
                        }                        
                    }
                    else {
                        $(".bt-w-main .plugin_body").html(shtml);
                    }
                    new Function(_item['name'] + '.init()')()
                })
            }
            else {
                $(".bt-w-main .plugin_body").html(shtml);
            }
        });
        if (menu_data) {
            $('.men_' + menu_data['name']).click();
        }
        else {
            $('.alarm-view .bt-w-menu p').eq(0).trigger('click')
        }
    })
}

function open_three_channel_auth() {

    layer.open({
        type: 1,
        area: "600px",
        title: "设置消息通道",
        closeBtn: 2,
        shift: 5,
        shadeClose: false,
        content: '<div class="bt-form alarm-view">\
                            <div class="bt-w-main" >\
                                <div class="bt-w-menu"></div>\
                                <div class="bt-w-con pd15">\
                                    <div class="plugin_body">\
                                    </div>\
                                </div>\
                         </div>\
                    </div >',
        success: function () {
            get_msg_config();
        }
    })
}


function modify_basic_auth_to() {
    var pdata = {
        open: $("select[name='open']").val(),
        basic_user: $("input[name='basic_user']").val(),
        basic_pwd: $("input[name='basic_pwd']").val()
    }
    var loadT = layer.msg('正在配置BasicAuth服务，请稍候...', { icon: 16, time: 0, shade: [0.3, '#000'] });
    $.post('/config?action=set_basic_auth', pdata, function (rdata) {
        layer.close(loadT);
        if (rdata.status) {
            layer.closeAll();
            setTimeout(function () { window.location.reload(); }, 3000);
        }
        layer.msg(rdata.msg, { icon: rdata.status ? 1 : 2 });
    });

}

function get_user_group(){
	layer.open({
		type: 1,
		area: ["600px","550px"],
		title: "多用户管理",
		closeBtn: 2,
		shift: 5,
		shadeClose: false,
		content: '<div class="bt-table pd20">\
				<div class="" style="overflow: hidden;margin-bottom: 10px;"><div class="pull-left"><button class="btn btn-success btn-sm add_users">添加用户</button></div><div class="pull-right" style="display:none"><input type="text" class="ser-text pull-left" placeholder="面板用户名" style="width:200px;margin-top:0;" /><button type="button" class="ser-sub pull-left" style="margin-top:0;"></button></div></div>\
				<div class="divtable mtb10" style="height:330px">\
					<table class="table table-hover">\
						<thead><tr><th width="150">用户名</th><th>类型</th><th style="text-align:right;">操作</th></tr></thead>\
						<tbody id="panel_user_list"></tbody>\
					</table>\
				</div>\
				<ul class="help-info-text c7">\
					<li>当前多用户管理仅支持操作记录，不支持权限分配，请须知。</li>\
					<li>面板日志、操作记录仅管理员可操作，子管理员仅支持查看，其他面板功能无限制。</li>\
					<li>多用户管理仅管理员账号可操作，子管理员无法操作。</li>\
				</ul>\
			</div>',
		success:function(layers,index){
			get_user_req();
			$('.add_users').click(function(){
				user_manage_view(true,{username:''});
			});
			$('#panel_user_list').on('click','.edit_user',function(){
				var _id = $(this).attr('data-id'),_user = $(this).attr('data-username');
				user_manage_view(false,{username:_user,id:_id});
			});
			$('#panel_user_list').on('click','.del_user',function(){
				var _id = $(this).attr('data-id'),_user = $(this).attr('data-username');
				if(_id == 1) {
					layer.msg('管理员账号无法删除',{icon:0});
					return false;
				}
				layer.confirm('是否删除当前用户:'+ _user +',是否继续？',{btn:['确认','取消'],icon:3,closeBtn: 2,title:'删除用户'},function(){
					del_user_req({id:_id},function(res){
						if(res.status){
							get_user_req(function(){layer.msg(res.msg,{icon:1});});
						}else{
							layer.msg(res.msg,{icon:2});
						}
					});
				});
			});
		}
	});
}
function user_manage_view(type,data){
	layer.open({
		type: 1,
		area:"400px",
		title: type?'添加用户或密码':'编辑用户或密码',
		closeBtn: 2,
		shift: 5,
		shadeClose: false,
		btn:[(type?'提交':'保存'),'取消'],
		content:'<div class="bt-form bt-form" style="padding:15px 25px">\
				<div class="line">\
					<span class="tname" style="width:100px">用户名</span>\
					<div class="info-r">\
						<input name="manage_user" class="bt-input-text mr5" type="text" style="width: 200px" value="'+ data.username +'" placeholder="请设置用户名" />\
					</div>\
				</div>\
				<div class="line">\
					<span class="tname" style="width:100px">密码</span>\
					<div class="info-r">\
						<input name="manage_pwd" class="bt-input-text mr5" type="text" style="width: 200px" value="" placeholder="'+ (type?"请设置用户名密码":"为空则不修改密码") +'">\
					</div>\
				</div>\
			</div>',
		yes:function(index,layers){
			var user = $('[name=manage_user]').val(),paw = $('[name=manage_pwd]').val();
			if(user == ''){
				layer.msg('用户名不能为空',{icon:2});
				return false;
			}
			if(type){
				if(paw == ''){
					layer.msg('用户名密码不能为空',{icon:2});
					return false;
				}
				add_user_req({username:user,password:paw},function(res){
					if(res.status){
						layer.close(index);
						get_user_req(function(){layer.msg(res.msg,{icon:1});});
					}else{
						layer.msg(res.msg,{icon:2});
					}
				});
			}else{
				modify_user_req({id:data.id,username:user,password:paw},function(res){
					if(res.status){
						layer.close(index);
						get_user_req(function(){layer.msg(res.msg,{icon:1});});
					}else{
						layer.msg(res.msg,{icon:2});
					}
				});
			}
		},
	});
}
get_user_req();
function get_user_req(callback){
	var loadT = layer.msg('正在获取用户列表中,请稍候...', { icon: 16, time: 0, shade: [0.3, '#000'] });
	$.post('/config?action=get_users',function(res){
		if(callback) callback(res)
		layer.close(loadT);
		var _html = '',_list = '';
		for(var i=0;i<res.length;i++){
			_html += '<tr><td>'+ res[i].username +'</td><td>'+ (res[i].id == 1?'管理员':'子管理员') +'</td><td style="text-align:right;"><a href="javascript:;" class="btlink edit_user" data-id="'+ res[i].id  +'" data-username="'+ res[i].username  +'">修改</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="javascript:;" class="btlink del_user" data-username="'+ res[i].username  +'" data-id="'+ res[i].id +'">删除</a></td></tr>';
			_list += res[i].username +'、'
		}
		$('[name="user_group"]').val(_list);
		$('#panel_user_list').html(_html);
	});
}
function add_user_req(data,callback){
	var loadT = layer.msg('正在添加用户,请稍候...', { icon: 16, time: 0, shade: [0.3, '#000'] });
	$.post('/config?action=create_user',{username:data.username,password:data.password},function(res){
		layer.close(loadT);
		if(callback) callback(res);
	});
}
function modify_user_req(data,callback){
	var loadT = layer.msg('正在修改用户,请稍候...', { icon: 16, time: 0, shade: [0.3, '#000'] });
	$.post('/config?action=modify_user',{id:data.id,username:data.username,password:data.password},function(res){
		layer.close(loadT);
		if(callback) callback(res);
	});
}
function del_user_req(data,callback){
	if(data['id'] === 1){
		layer.msg('当前用户为管理员用户，无法删除',{icon:0});
		return false;
	}
	var loadT = layer.msg('正在删除用户,请稍候...', { icon: 16, time: 0, shade: [0.3, '#000'] });
	$.post('/config?action=remove_user',{id:data.id},function(res){
		layer.close(loadT);
		if(callback) callback(res);
	});
}
function modify_basic_auth() {
    var loadT = layer.msg('正在获取配置,请稍候...', { icon: 16, time: 0, shade: [0.3, '#000'] });
    $.post('/config?action=get_basic_auth_stat', {}, function (rdata) {
        layer.close(loadT);
        layer.open({
            type: 1,
            area: "500px",
            title: "配置BasicAuth认证",
            closeBtn: 2,
            shift: 5,
            shadeClose: false,
            content: ' <div class="bt-form bt-form" style="padding:15px 25px">\
						<div class="line">\
							<span class="tname">服务状态</span>\
							<div class="info-r" style="height:28px;">\
								<select class="bt-input-text" name="open">\
                                    <option value="True" '+ (rdata.open ? 'selected' : '') + '>开启</option>\
                                    <option value="False" '+ (rdata.open ? '' : 'selected') + '>关闭</option>\
                                </select>\
							</div>\
						</div>\
                        <div class="line">\
                            <span class="tname">用户名</span>\
                            <div class="info-r">\
                                <input name="basic_user" class="bt-input-text mr5" type="text" style="width: 310px" value="" placeholder="'+ (rdata.basic_user ? '不修改请留空' : '请设置用户名') + '">\
                            </div>\
                        </div>\
                        <div class="line">\
                            <span class="tname">密码</span>\
                            <div class="info-r">\
                                <input name="basic_pwd" class="bt-input-text mr5" type="text" style="width: 310px" value="" placeholder="'+ (rdata.basic_pwd ? '不修改请留空' : '请设置密码') + '">\
                            </div>\
                        </div>\
                        <span><button class="btn btn-success btn-sm" style="    margin-left: 340px;" onclick="modify_basic_auth_to()">保存配置</button></span>\
                        <ul class="help-info-text c7">\
                            <li style="color:red;">注意：请不要在这里使用您的常用密码，这可能导致密码泄漏！</li>\
                            <li>开启后，以任何方式访问面板，将先要求输入BasicAuth用户名和密码</li>\
                            <li>开启后，能有效防止面板被扫描发现，但并不能代替面板本身的帐号密码</li>\
                        </ul>\
                    </div>'
        })
    });
}



/**
 * @description 获取临时授权列表
 * @param {Function} callback 回调函数列表
 * @returns void
 */
function get_temp_login(data, callback) {
    var loadT = bt.load('获取临时授权列表，请稍后...');
    bt.send('get_temp_login', 'config/get_temp_login', data, function (res) {
        if (res.status === false) {
            layer.closeAll();
            bt.msg(res);
            return false;
        }
        loadT.close();
        if (callback) callback(res)
    });
}

/**
 * @description 设置临时链接
 * @param {Function} callback 回调函数列表
 * @returns void
 */
function set_temp_login(callback) {
    var loadT = bt.load('正在设置临时链接，请稍后...');
    bt.send('set_temp_login', 'config/set_temp_login', {}, function (res) {
        loadT.close();
        if (callback) callback(res)
    });
}

/**
 * @description 设置临时链接
 * @param {Object} data 传入参数，id
 * @param {Function} callback 回调函数列表
 * @returns void
*/
function remove_temp_login(data, callback) {
    var loadT = bt.load('正在删除临时授权记录，请稍后...');
    bt.send('remove_temp_login', 'config/remove_temp_login', { id: data.id }, function (res) {
        loadT.close();
        if (callback) callback(res)
    });
}
/**
 * @description 强制用户登出
 * @param {Object} data 传入参数，id
 * @param {Function} callback 回调函数列表
 * @returns void
*/
function clear_temp_login(data, callback) {
    var loadT = bt.load('正在强制用户登出，请稍后...');
    bt.send('clear_temp_login', 'config/clear_temp_login', { id: data.id }, function (res) {
        loadT.close();
        if (callback) callback(res)
    });
}

/**
 * @description 渲染授权管理列表
 * @param {Object} data 传入参数，id
 * @param {Function} callback 回调函数列表
 * @returns void
*/
function reader_temp_list(data, callback) {
    if (typeof data == 'function') callback = data, data = { p: 1 };
    get_temp_login(data, function (rdata) {
        var html = '';
        $.each(rdata.data, function (index, item) {
            html += '<tr><td>' + (item.login_addr || '未登录') + '</td><td>' + (function () {
                switch (item.state) {
                    case 0:
                        return '<a style="color:green;">待使用</a>';
                        break;
                    case 1:
                        return '<a style="color:brown;">已使用</a>';
                        break;
                    case -1:
                        return '<a>已过期</a>';
                        break;
                }
            }()) + '</td><td >' + (item.login_time == 0 ? '未登录' : bt.format_data(item.login_time)) + '</td><td>' + bt.format_data(item.expire) + '</td><td style="text-align:right;">' + (function () {
                if (item.state != 1) {
                    return '<a href="javascript:;" class="btlink remove_temp_login" data-ip="' + item.login_addr + '" data-id="' + item.id + '">删除</a>';
                }
                if (item.online_state) {
                    return '<a href="javascript:;" class="btlink clear_temp_login" style="color:red" data-ip="' + item.login_addr + '" data-id="' + item.id + '">强制登出</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="javascript:;" class="btlink logs_temp_login" data-ip="' + item.login_addr + '" data-id="' + item.id + '">操作日志</a>';
                }
                return '<a href="javascript:;" class="btlink logs_temp_login" data-ip="' + item.login_addr + '" data-id="' + item.id + '">操作日志</a>';
            }()) + '</td></tr>';
        });
        $('#temp_login_view_tbody').html(html);
        $('.temp_login_view_page').html(rdata.page);
        if (callback) callback()
    });
}




/**
 * @description 获取操作日志
 * @param {Object} data 传入参数，id
 * @param {Function} callback 回调函数列表
 * @returns void
*/
function get_temp_login_logs(data, callback) {
    var loadT = bt.load('正在获取操作日志，请稍后...');
    bt.send('clear_temp_login', 'config/get_temp_login_logs', { id: data.id }, function (res) {
        loadT.close();
        if (callback) callback(res)
    });
}

/**
 * @description 渲染操作日志
 * @param {Object} data 传入参数，id
 * @param {Function} callback 回调函数列表
 * @returns void
*/
function reader_temp_login_logs(data, callback) {
    get_temp_login_logs(data, function (res) {
        var html = '';
        $.each(res, function (index, item) {
            html += '<tr><td>' + item.type + '</td><td>' + item.addtime + '</td><td><span title="' + item.log + '" style="white-space: pre;">' + item.log + '</span></td></tr>';
        });
        if (callback) callback({ tbody: html, data: res });
    })
}




/**
 * @description 设置临时链接
 * @param {Function} callback 回调函数列表
 * @returns void
*/
function get_temp_login_view() {
    layer.open({
        type: 1,
        area: ["700px", '600px'],
        title: "临时授权管理",
        closeBtn: 2,
        shift: 5,
        shadeClose: false,
        content: '<div class="login_view_table pd15">' +
            '<button class="btn btn-success btn-sm va0 create_temp_login" >创建临时授权</button>' +
            '<div class="divtable mt10">' +
            '<table class="table table-hover">' +
            '<thead><tr><th>登录IP</th><th>状态</th><th>登录时间</th><th>过期时间</th><th style="text-align:right;">操作</th></tr></thead>' +
            '<tbody id="temp_login_view_tbody"></tbody>' +
            '</table>' +
            '<div class="temp_login_view_page page"></div>' +
            '</div>' +
            '</div>',
        success: function () {
            reader_temp_list();
            // 创建临时授权
            $('.create_temp_login').click(function () {
                bt.confirm({ title: '风险提示', msg: '<span style="color:red">注意1：滥用临时授权可能导致安全风险。</br>注意2：请勿在公共场合发布临时授权连接</span></br>即将创建临时授权连接，继续吗？' }, function () {
                    layer.open({
                        type: 1,
                        area: '650px',
                        title: "创建临时授权",
                        closeBtn: 2,
                        shift: 5,
                        shadeClose: false,
                        content: '<div class="bt-form create_temp_view">' +
                            '<div class="line"><span class="tname">临时授权地址</span><div class="info-r ml0"><textarea id="temp_link" class="bt-input-text mr20" style="margin: 0px;width: 500px;height: 50px;line-height: 19px;"></textarea></div></div>' +
                            '<div class="line"><button type="submit" class="btn btn-success btn-sm btn-copy-temp-link" data-clipboard-text="">复制地址</button></div>' +
                            '<ul class="help-info-text c7"><li>临时授权生成后1小时内使用有效，为一次性授权，使用后立即失效</li><li>使用临时授权登录面板后1小时内拥有面板所有权限，请勿在公共场合发布临时授权连接</li><li>授权连接信息仅在此处显示一次，若在使用前忘记，请重新生成</li></ul>' +
                            '</div>',
                        success: function () {
                            set_temp_login(function (res) {
                                if (res.status) {
                                    var temp_link = location.origin + '/login?tmp_token=' + res.token;
                                    $('#temp_link').val(temp_link);
                                    $('.btn-copy-temp-link').attr('data-clipboard-text', temp_link);
                                }
                            });
                            var clipboard = new ClipboardJS('.btn');
                            clipboard.on('success', function (e) {
                                bt.msg({ status: true, msg: '复制成功！' });
                                e.clearSelection();
                            });
                            clipboard.on('error', function (e) {
                                bt.msg({ status: false, msg: '复制失败，请手动复制地址' });
                            });
                        },
                        end: function () {
                            reader_temp_list();
                        }
                    });
                });
            });
            // 操作日志
            $('#temp_login_view_tbody').on('click', '.logs_temp_login', function () {
                var id = $(this).data('id'), ip = $(this).data('ip');
                layer.open({
                    type: 1,
                    area: ['700px', '550px'],
                    title: '查看操作日志[' + ip + ']',
                    closeBtn: 2,
                    shift: 5,
                    shadeClose: false,
                    content: '<div class="pd15">' +
                        '<button class="btn btn-default btn-sm va0 refresh_login_logs">刷新日志</button>' +
                        '<div class="divtable mt10 tablescroll" style="max-height: 420px;overflow-y: auto;border:none">' +
                        '<table class="table table-hover" id="logs_login_view_table">' +
                        '<thead><tr><th width="90px">操作类型</th><th width="140px">操作时间</th><th>日志</th></tr></thead>' +
                        '<tbody ></tbody>' +
                        '</table>' +
                        '</div>' +
                        '</div>',
                    success: function () {
                        reader_temp_login_logs({ id: id }, function (data) {
                            $('#logs_login_view_table tbody').html(data.tbody);
                        });
                        $('.refresh_login_logs').click(function () {
                            reader_temp_login_logs({ id: id }, function (data) {
                                $('#logs_login_view_table tbody').html(data.tbody);
                            });
                        });
                        bt.fixed_table('logs_login_view_table');
                    }
                });
            });

            //删除授权记录，仅未使用的授权记录
            $('#temp_login_view_tbody').on('click', '.remove_temp_login', function () {
                var id = $(this).data('id');
                bt.confirm({
                    title: '删除未使用授权',
                    msg: '是否删除未使用授权记录，是否继续？'
                }, function () {
                    remove_temp_login({ id: id }, function (res) {
                        reader_temp_list(function () {
                            bt.msg(res);
                        })
                    })
                })
            });

            //强制下线，强制登录的用户下线
            $('#temp_login_view_tbody').on('click', '.clear_temp_login', function () {
                var id = $(this).data('id'), ip = $(this).data('ip');
                bt.confirm({
                    title: '强制登出[ ' + ip + ' ]',
                    msg: '是否强制登出[ ' + ip + ' ]，是否继续？'
                }, function () {
                    clear_temp_login({ id: id }, function (res) {
                        reader_temp_list(function () {
                            bt.msg(res);
                        });
                    });
                })
            });
            // 分页操作
            $('.temp_login_view_page').on('click', 'a', function (ev) {
                var href = $(this).attr('href'), reg = /([0-9]*)$/, page = reg.exec(href)[0];
                reader_temp_list({ p: page });
                ev.stopPropagation();
                ev.preventDefault();
            });
        }
    });

}


